<?php

namespace app\manage\controller;

use app\BaseController;
use app\manage\services\Login as LoginService;
use app\manage\validate\Login as LoginValidate;
use think\captcha\facade\Captcha;
use think\facade\Request;
use think\Response;
use think\response\Json;
use hg\apidoc\annotation as Apidoc;
use think\App;

/**
 * @Apidoc\Title("登录模块")
 */
class Login extends BaseController
{
    protected $service;
    protected $validate;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->service = new LoginService();
        $this->validate = new LoginValidate();
    }

    /**
     * @Apidoc\Title("登录")
     * @Apidoc\Desc("登录接口")
     * @Apidoc\Url("/manage/login")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("username", type="string",require=true, desc="用户名" )
     * @Apidoc\Param("password", type="string",require=true, desc="密码" )
     * @Apidoc\Param("captcha", type="string",require=true, desc="验证码" )
     * @Apidoc\Returned("token", type="string", desc="登录token")
     * @Apidoc\Returned("expire", type="int", desc="token时效")
     */
    public function index(Request $request): Json
    {
        if ($request::isPost()) {
            if (!empty($this->validate)) {
                $this->validate->goCheck('login');
            }
            $params = $request::post();
            $res = $this->service->login($params);
            switch ($res) {
                case -1:
                    return jsonE('验证码错误');
                case -2:
                    return jsonE('账号错误');
                case -3:
                    return jsonE('密码错误');
                default:
                    return jsonT($res);
            }
        }
        return jsonE('非法请求');
    }

    /**
     * @Apidoc\Title("验证码")
     * @Apidoc\Desc("获取验证码")
     * @Apidoc\Url("/manage/verify")
     * @Apidoc\Method("GET")
     */
    public function verify(): Response
    {
        return Captcha::create();
    }
}
